home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / listings / v_12_07 / letters / badfree.c < prev   
C/C++ Source or Header  |  1994-06-05  |  1KB  |  59 lines

  1. /* free function */
  2. #include "xalloc.h"
  3.  
  4. void (free)(void *ptr)
  5.     {
  6.     /* free an allocated data object */
  7.     _Cell *q;
  8.  
  9.     if (ptr == NULL)
  10.         return;
  11.     q = (_Cell *) ((char *)ptr - CELL_OFF);
  12.     if (q->_Size & _MEMBND)
  13.         return;
  14.         /* bad pointer */
  15.     if (_Aldata._Head == NULL
  16.         || q < _Aldata._Head)
  17.         {
  18.         /* insert at head of list */
  19.         q->_Next = _Aldata._Head;
  20.         _Aldata._Head = q;
  21.         }
  22.     else
  23.         {
  24.         /* Scan for insertion point */
  25.         _Cell *qp;
  26.         char *qpp;
  27.  
  28.         for (qp = _Aldata._Head;
  29.             qp->_Next && q < qp-_Next; )
  30.             /* < TEST IS BACKWARDS */
  31.             qp = qp-> Next;
  32.         qpp = (char *) qp + CELL_OFF + qp->_Size;
  33.         if ((char *) q < qpp)
  34.             return;
  35.             /* erroneous call */
  36.         else if ((char *)q == qpp)
  37.             {
  38.             /* merge qp and q */
  39.             qp->_Size += CELL_OFF + q->_Size;
  40.             q = qp;
  41.             }
  42.         else
  43.             {
  44.             /* splice q after qp */
  45.             q->_Next = qp->_Next;
  46.             qp->_Next = q;
  47.             }
  48.         }
  49.     if (q->_Next &&
  50.         (char *) q + CELL_OFF + q->_Size
  51.          == (char *)q->_Next)
  52.         {
  53.         q->_Size += CELL_OFF + q->_Next->_Size;
  54.         q->_Next = q->_Next->_Next;
  55.         }
  56.      _Aldata._Plast = &q->_Next;
  57.       /* resume scan after freed */
  58.      }
  59.